package net.hancl.modules.sys.shiro;

import net.hancl.common.utils.spring.SysApplicationContext;
import net.hancl.modules.sys.entity.User;
import net.hancl.modules.sys.service.IRoleService;
import net.hancl.modules.sys.service.IUserLoginService;
import net.hancl.modules.sys.service.IUserService;
import net.hancl.modules.sys.utils.PassUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserLoginService userLoginService;

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    //	@Autowired
    private PassUtil passUtil;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        if (userLoginService == null) {
            userLoginService = (IUserLoginService) SysApplicationContext
                    .getBean("userLoginService");
        }

        if(userService==null){
            userService =  (IUserService) SysApplicationContext
                    .getBean("userService");
        }

        // userService.findRoles(username)
        Set<String> roles = userService.getUserRole(username);
        authorizationInfo.setRoles(roles);
        // userService.findPermissions(username)
        Set<String> permissions = userService.getUserPermissions(username);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String)token.getPrincipal();
        User user = userLoginService.getUser(username);
        if(user == null){
            throw new UnknownAccountException();
        }
        if(user.getStatus() == 2){
            throw new LockedAccountException();
        }
        ByteSource byteSource = ByteSource.Util.bytes(PassUtil.SALT + user.getUserName());
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), byteSource, getName());

        return info;
    }
}
